package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.Data.Scan;
import com.example.myapplication.Network.NetAction;
import com.example.myapplication.Network.NetType;
import com.example.myapplication.Network.UdpClient;
import com.example.myapplication.Network.UdpListener;

import org.json.JSONException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Button scanBtn =  findViewById(R.id.scanBtn);
        scanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ip = NetAction.brocastAddress(MainActivity.this);
                int port = 13532;

                Scan scan = new Scan("android",NetAction.getWifiIPAddress(MainActivity.this), NetType.SCAN_MESSAGE_REQ.getDescription());

                UdpClient udpClient = new UdpClient();
                udpClient.ipAddress = ip;
                udpClient.port = port;
                try {
                    udpClient.message = scan.encodeToJson();
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }


                new Thread(udpClient).start();




                Intent intent = new Intent();
                intent.setClass(MainActivity.this,ScanList.class);
                startActivity(intent);
            }
        });

        UdpListener udpListener = new UdpListener();
        new Thread(udpListener).start();

    }
}